import 'package:FlutterStudy/utils/splash.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

// MARK: - 1. 定义路由配置（AppRoutePath）
// 用于表示应用的导航状态
abstract class AppRoutePath {}

class HomePagePath extends AppRoutePath {}

class DetailsPagePath extends AppRoutePath {
  final String id;
  DetailsPagePath(this.id);
}

class UnknownPagePath extends AppRoutePath {}

// MARK: - 2. RouteInformationParser
// 负责将URL路径解析为AppRoutePath，或将AppRoutePath转回URL路径
class MyRouteInformationParser extends RouteInformationParser<AppRoutePath> {
  // 将URL路径解析为AppRoutePath
  @override
  Future<AppRoutePath> parseRouteInformation(
      RouteInformation routeInformation) async {
    final uri = Uri.parse(routeInformation.uri.path);
    print('将URL路径解析为AppRoutePath: ${uri.path}');

    if (uri.pathSegments.isEmpty) {
      return HomePagePath();
    }
    if (uri.pathSegments.length == 2 && uri.pathSegments[0] == 'details') {
      return DetailsPagePath(uri.pathSegments[1]);
    }
    return UnknownPagePath();
  }

  // 将AppRoutePath转回URL路径，用于更新浏览器URL
  @override
  RouteInformation? restoreRouteInformation(AppRoutePath configuration) {
    print('将AppRoutePath转回URL路径，用于更新浏览器URL: ${configuration}');
    if (configuration is HomePagePath) {
      return  RouteInformation(uri: Uri.parse('/'));
    }
    if (configuration is DetailsPagePath) {
      return RouteInformation(uri: Uri.parse('/details/${configuration.id}'));
    }
    return null; // 对于UnknownPagePath，不提供URL
  }
}

// MARK: - 3. RouterDelegate
// 负责根据AppRoutePath构建页面堆栈，并通知路由信息提供者
class MyRouterDelegate extends RouterDelegate<AppRoutePath>
    with ChangeNotifier, PopNavigatorRouterDelegateMixin<AppRoutePath> {
  final GlobalKey<NavigatorState> _navigatorKey;

  MyRouterDelegate() : _navigatorKey = GlobalKey<NavigatorState>();

  AppRoutePath _currentPath = HomePagePath();

  @override
  GlobalKey<NavigatorState> get navigatorKey => _navigatorKey;

  // 获取当前路由配置，用于浏览器书签和历史记录
  @override
  AppRoutePath get currentConfiguration => _currentPath;

  // 当浏览器URL改变时（例如返回键），RouteInformationParser解析后会调用此方法
  @override
  Future<void> setNewRoutePath(AppRoutePath configuration) async {
     print('当浏览器URL改变时: $configuration');
    if (configuration is DetailsPagePath) {
      _currentPath = configuration;
    } else if (configuration is HomePagePath) {
      _currentPath = configuration;
    } else {
      _currentPath = UnknownPagePath();
    }
    notifyListeners(); // 通知Router重建
  }

  // 处理页面弹出事件
  @override
  Future<bool> popRoute() async {
    print('弹出事件');
    if (_currentPath is DetailsPagePath) {
      _currentPath = HomePagePath();
      notifyListeners();
      return SynchronousFuture(true); // 消费了弹出事件
    }
    if (_currentPath is UnknownPagePath) {
      _currentPath = HomePagePath();
      notifyListeners();
      return SynchronousFuture(true);
    }
    return SynchronousFuture(false); // 未消费弹出事件，让系统处理（例如退出应用）
  }

  // 构建页面堆栈
  @override
  Widget build(BuildContext context) {
    return Navigator(
      key: navigatorKey,
      pages: [
        // 首页
        MaterialPage(
          key: const ValueKey('HomePage'),
          child: HomeScreen(
            onViewDetails: (id) {
              _currentPath = DetailsPagePath(id);
              notifyListeners(); // 导航到详情页时，通知Router更新URL
            },
          ),
        ),
        // 详情页（如果当前路径是详情页）
        if (_currentPath is DetailsPagePath)
          MaterialPage(
            key: ValueKey('DetailsPage-${(_currentPath as DetailsPagePath).id}'),
            child: DetailsScreen(id: (_currentPath as DetailsPagePath).id),
          ),
        // 未知页（如果当前路径是未知页）
        if (_currentPath is UnknownPagePath)
          const MaterialPage(
            key: ValueKey('UnknownPage'),
            child: UnknownScreen(),
          ),
      ],
      onPopPage: (route, result) {
        if (!route.didPop(result)) {
          return false;
        }
        // 当页面被弹出时，更新内部状态
        if (_currentPath is DetailsPagePath) {
          _currentPath = HomePagePath();
        } else if (_currentPath is UnknownPagePath) {
          _currentPath = HomePagePath();
        }
        notifyListeners(); // 通知Router更新URL
        return true;
      },
    );
  }
}

// MARK: - 4. UI 页面
class MyApp extends StatelessWidget  with Splash{
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    hideScreen();
    return MaterialApp.router(
      title: 'Flutter Navigator 2.0 Web Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      routeInformationParser: MyRouteInformationParser(),
      routerDelegate: MyRouterDelegate(),
      // 确保使用PlatformRouteInformationProvider来处理Web上的URL
      routeInformationProvider: PlatformRouteInformationProvider(
        initialRouteInformation:  RouteInformation(uri: Uri.parse('/')),
      ),
    );
  }
}

class HomeScreen extends StatelessWidget {
  final ValueChanged<String> onViewDetails;

  const HomeScreen({super.key, required this.onViewDetails});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Home Screen')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text('Welcome to the Home Screen!'),
            ElevatedButton(
              onPressed: () => onViewDetails('123'),
              child: const Text('View Details for Item 123'),
            ),
            ElevatedButton(
              onPressed: () => onViewDetails('456'),
              child: const Text('View Details for Item 456'),
            ),
          ],
        ),
      ),
    );
  }
}

class DetailsScreen extends StatelessWidget {
  final String id;

  const DetailsScreen({super.key, required this.id});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Details Screen for Item $id')),
      body: Center(
        child: Text('You are viewing details for item: $id'),
      ),
    );
  }
}

class UnknownScreen extends StatelessWidget {
  const UnknownScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Page Not Found')),
      body: const Center(
        child: Text('404 - Page not found!'),
      ),
    );
  }
}